package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
        @Autowired
        private DishMapper dishMapper;
        @Autowired
        private DishFlavorMapper dishFlavorMapper;
        @Autowired
        private CategoryMapper categoryMapper;
        @Autowired
        private SetmealDishMapper setmealDishMapper;
        @Autowired
        private StringRedisTemplate stringRedisTemplate;

        /**
         * 新增菜品
         *
         * @param dto
         * @return
         */
        @Override
        public Result addDish( DishDTO dto) {
            //1.参数校验
            if (dto.getCategoryId() == null){
                return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
            }
            //2.新增菜品表,一条数据,当事务没有提交之前,必须返回id,供新增口味使用
            Dish dish = new Dish();
            BeanUtils.copyProperties(dto,dish);
            dishMapper.insertDish(dish);

            //3.新增口味集合,多条数据,执行批量新增,拿到菜品id
            List<DishFlavor> flavors = dto.getFlavors();

            if (flavors==null&&flavors.size()==0){
                flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
                dishFlavorMapper.insertDishFlavor(flavors);
            }

            //清理缓存
            String pattern = "dish_"+dish.getCategoryId();
            cleanCache(pattern);

            //返回参数
            return Result.success();
        }

    /**
     * 分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public Result pageDish(DishPageQueryDTO dishPageQueryDTO) {
        //1.非空判断
        if (dishPageQueryDTO.getPage() == null){
            dishPageQueryDTO.setPage(1);
        }

        if (dishPageQueryDTO.getPageSize() == null){
            dishPageQueryDTO.setPageSize(5);
        }
        //2.分页开启
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //3.调用mapper
        Page<Dish> page = dishMapper.page(dishPageQueryDTO);

        //3.1总条数及菜品集合
        long total = page.getTotal();
        List<Dish> dishList = page.getResult();

        //3.3声明一个List用来承载vo对象集合
        List<DishVO> dishVoList = new ArrayList(dishList.size());

        //3.2为每一条数据添加菜品分类名称
        dishList.forEach(dish -> {
            //1.声明一个vo对象
            DishVO vo = new DishVO();
            BeanUtils.copyProperties(dish,vo);
            //2.获取分类名称
            Category category = categoryMapper.getById(vo.getCategoryId());
            vo.setCategoryName(category.getName());
            //3.写入数据到voList
            dishVoList.add(vo);
        });

        //4.返回数据
        PageResult pageResult = new PageResult();
        pageResult.setRecords(dishVoList);
        pageResult.setTotal(total);

        return Result.success(pageResult);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public Result deleteDish(List<Long> ids) {
        //1.校验参数
        if (ids == null || ids.size() == 0){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.查询当前菜品是否存在
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            //3.如果存在,判断状态如果是起售状态,则不能删除
            if (dish!=null){
                if (dish.getStatus() == StatusConstant.ENABLE){
                    return Result.error(MessageConstant.DISH_ON_SALE);
                }
            }
        }

        //4.如果存在,被套餐关联的话也不能删除
        List<Long> SetmealDishIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (SetmealDishIds!= null && SetmealDishIds.size()>0){
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //5.如果存在,删除菜品之后,口味数据也删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);

        //清理缓存
        String pattern = "dish_*";
        cleanCache(pattern);

        //3.返回数据
        return Result.success();
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO selectId(Long id) {
//        //1.非空校验
//        if (id == null){
//            return Result.error(MessageConstant.ID_NOT_FOUND);
//        }
        //2.根据菜品id查询菜品的数据
        Dish dish = dishMapper.getById(id);

        //3.根据菜品id查询口味的数据
        List<DishFlavor> flavor = dishFlavorMapper.getDishId(id);

        //4.将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavor);

        //3.返回参数
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result updateDish(DishDTO dto) {
        //1.非空校验
        if (dto.getCategoryId() == null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.创建Dish实体,获取id查询到的菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.updateDish(dish);

        //3.删除口味关联表
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dish.getId()));

        //4.新增口味关联表
        List<DishFlavor> flavors = dto.getFlavors();
//        if (flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
//        }

        //5.遍历插入
        dishFlavorMapper.insertDishFlavor(flavors);

        //清理缓存
        String pattern = "dish_"+dish.getCategoryId();
        cleanCache(pattern);

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public Result selectDish(Long id,String name) {
        //1.非空校验(判断id下的菜品是否存在)
        if (id == null && name ==null){
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        Dish dish=new Dish();
        dish.setStatus(StatusConstant.ENABLE);
        dish.setCategoryId(id);
        dish.setName(name);
        //2.创建对象,拿到id下的菜品
        //3.把拿到的所有菜品存入集合中
        List<Dish> dishBycategoryId = dishMapper.getDishBycategoryId(dish);

        //4.返回数据
        return Result.success(dishBycategoryId);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        String key = "dish_" + dish.getCategoryId();
        //首先去查询redis,如果redis中有数据,则直接返回
        String dishVoListStr = stringRedisTemplate.opsForValue().get(key);
        //把字符串转成list集合
        List<DishVO> dishVOListForRedis = JSONArray.parseArray(dishVoListStr, DishVO.class);
        if (dishVOListForRedis != null && dishVOListForRedis.size() > 0){
            return dishVOListForRedis;
        }
        //否则,没有数据,查询mysql,写入数据到redis中
        //条件查询对应的菜品集合
        List<Dish> dishList = dishMapper.list(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        //写入数据到redis
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));

        return dishVOList;
    }

    private void cleanCache(String pattern){
        Set<String> keys = stringRedisTemplate.keys(pattern);
        stringRedisTemplate.delete(keys);

    }
}
